import axios, { AxiosError, AxiosInstance } from 'axios';
import JSONbig from 'json-bigint';
import store from '../store/store';
import { resultHandler } from './result-handle';
import { Toast } from '@douyinfe/semi-ui';

axios.defaults.withCredentials = true;
// @ts-ignore
axios.defaults.crossDomain = true;

axios.defaults.baseURL = import.meta.env.VITE_REACT_APP_URL;

// instance for axios
const service: AxiosInstance = axios.create({
  timeout: 35000, // 请求超时时间
  transformResponse: [
    function (data) {
      if (data && typeof data === 'string') {
        const JSONbigString = JSONbig({ storeAsString: true });
        return JSONbigString.parse(data);
      } else {
        return data;
      }
    },
  ],
});

// cancel request
const cancelToken = axios.CancelToken;
const source = cancelToken.source();

// request interceptor
service.interceptors.request.use(
  (config) => {
    // if (config.method === "get" && config.data && !config.params) {
    // 	config.params = config.data;
    // }
    // config.withCredentials = true;

    // logic to cancel token
    // source.cancel();

    const {
      auth: { userToken },
    } = store.getState();

    if (userToken && config.headers) {
      config.headers['mrktcoopToken'] = userToken;
    }
    config.cancelToken = source.token;

    return config;
  },
  (error) => Promise.reject(error)
);

// response interceptor
service.interceptors.response.use(
  (response) => {
console.log()
    switch (response.data.code) {
			// 没有权限
			case 401: {
        window.location.pathname = '/login';
			}
		}

		resultHandler(response);
	
		return response;
  },
  (error) => {
    // cancel request
    if (axios.isCancel(error)) {
      console.log('Request canceled', error.message);
    } else {
      // 处理错误 提示 根据请求返回状态码分别处理
      switch (error?.response?.status) {
        case 400: {
          const { message } = error.response.data;
					Toast.error(`操作失败 - ${message ? message : "未知错误"}`);
          break;
        }
        case 401: {
          console.log('handle 401 -> logout');
          console.log('request url', error.response.config.url);
          window.location.pathname = '/login';
          // store.dispatch(logout);
          break;
        }
        case 422: {
          break;
        }
        case 500: {
          break;
        }
        case 504: {
          break;
        }
        default:
          const { message } = error.response.data;
					Toast.error(`操作失败 - ${message ? message : "未知错误"}`);
          break;
      }
    }
    return Promise.reject(error);
  }
);

export default service;
